package com.zp.base.admin.controller;

import java.util.*;

import com.zp.base.admin.common.annotation.AddGroup;
import com.zp.base.admin.common.annotation.UpdateGroup;
import com.zp.base.admin.common.aspect.AddOperatorLog;
import com.zp.base.admin.common.constant.BizCodeEnum;
import com.zp.base.admin.common.utils.R;
import com.zp.base.admin.common.utils.ValidUtil;
import com.zp.base.admin.config.SiteConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.zp.base.admin.entity.MenuEntity;
import com.zp.base.admin.service.MenuService;



/**
 * 
 *
 * @author zhangpeng
 * @email zhangpeng@aliyun.com
 * @date 2021-02-28 11:15:56
 */
@Controller
@RequestMapping("admin/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private SiteConfig siteConfig;
    /**
     * 列表
     */
    @GetMapping("/list")
    @AddOperatorLog(content = "查看了菜单列表")
    @PreAuthorize("hasAuthority('menu:list')")
    public String list(Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<MenuEntity> menuEntityList = menuService.getAllMenus();
        model.addAttribute("menus", menuEntityList);
        model.addAttribute("title","菜单列表");
        model.addAttribute("siteName", siteConfig.getSiteName());
        return"admin/menu/list";
    }


    @GetMapping("/add")
    @PreAuthorize("hasAuthority('menu:add')")
    public String toAdd(Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<MenuEntity> menuEntityList = menuService.getAllMenus();

        model.addAttribute("menus", menuEntityList);
        model.addAttribute("title","菜单列表");
        model.addAttribute("siteName", siteConfig.getSiteName());
        return "admin/menu/add";
    }

    /**
     * 保存
     */
    @PostMapping("/add")
    @AddOperatorLog(content = "添加了菜单")
    @PreAuthorize("hasAuthority('menu:add')")
    @ResponseBody
    public R save(@Validated({AddGroup.class}) MenuEntity menu, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        boolean save = menuService.save(menu);
        if (!save) {
            return R.error(BizCodeEnum.ADD_MENU_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.ADD_MENU_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 去修改页面
     */
    @GetMapping("/edit")
    @PreAuthorize("hasAuthority('menu:edit')")
    public String toEdit(@RequestParam(name = "id") Long id, Model model){
        //获取所有一级菜单信息（包含子类菜单信息）
        List<MenuEntity> menuEntityList = menuService.getAllMenus();
        model.addAttribute("title","菜单列表");
        model.addAttribute("menus", menuEntityList);
        model.addAttribute("siteName", siteConfig.getSiteName());
        model.addAttribute("menu", menuService.getMenuById(id));
        return "admin/menu/edit";
    }

    /**
     * 修改
     */
    @PostMapping("/edit")
    @AddOperatorLog(content = "修改了菜单信息")
    @PreAuthorize("hasAuthority('menu:edit')")
    @ResponseBody
    public R edit(@Validated(UpdateGroup.class) MenuEntity menu, BindingResult bindingResult){
        //检查菜单信息  使用JSR303校验
        if (bindingResult.hasErrors()) {
            return ValidUtil.getErrorInfo(bindingResult);
        }
        menu.setUpdateTime(new Date());
        menu.setMenuPermission(null);  //不允许修改权限标志
        boolean b = menuService.updateById(menu);
        if (!b) {
            return R.error(BizCodeEnum.UPDATE_MENU_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.UPDATE_MENU_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @AddOperatorLog(content = "删除了菜单")
    @PreAuthorize("hasAuthority('menu:delete')")
    @ResponseBody
    public R delete(@RequestParam(name = "id")Long id){
        if (id == null) {
            return R.error(BizCodeEnum.DELETE_MENU_ID_NOT_NULL.getCode(), BizCodeEnum.DELETE_MENU_ID_NOT_NULL.getMsg());
        }
        //判断该菜单下是否有子菜单
        boolean b = menuService.getChildrenMenuByParentId(id);
        if (b) {
            //有子菜单不能删除
            return R.error(BizCodeEnum.DELETE_MENU_HAS_CHILDREN_MENU.getCode(), BizCodeEnum.DELETE_MENU_HAS_CHILDREN_MENU.getMsg());
        }
        //删除菜单
        boolean removeById = menuService.deleteMenuById(id);
        if (!removeById) {
            return R.error(BizCodeEnum.DELETE_MENU_FAIL_SERVER_EXCEPTION.getCode(), BizCodeEnum.DELETE_MENU_FAIL_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

}
